<?php
class Member {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 添加员工
     */
    public function create(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['username'])) {
            throw new Exception("员工用户名不能为空", 400);
        }
        if (empty($data['real_name'])) {
            throw new Exception("员工真实姓名不能为空", 400);
        }

        // 设置默认值
        $data['status'] = isset($data['status']) ? intval($data['status']) : 1;

        // 插入数据到users表
        $stmt = $this->conn->prepare("
            INSERT INTO users (
                username, real_name, position, 
                mobile,  status,
                create_time, sub_mobile
            ) VALUES (
                :username, :real_name, :position,
                :mobile, :status,
                NOW(), :sub_mobile
            )
        ");

        // 生成唯一的sub_mobile值
        $subMobile = 'member_' . time() . '_' . rand(1000, 9999);
        
        if (!$stmt->execute([
            ':username' => $data['username'],
            ':real_name' => $data['real_name'],
            ':position' => $data['position'] ?? null,
            ':mobile' => $data['mobile'] ?? null,
            ':status' => $data['status'],
            ':sub_mobile' => $subMobile
        ])) {
            throw new Exception("添加员工失败", 500);
        }

        echo json_encode([
            'code' => 200,
            'msg' => '添加成功',
            'data' => [
                'id' => $this->conn->lastInsertId(),
                'username' => $data['username'],
                'real_name' => $data['real_name']
            ]
        ]);
    }


    /**
     * 删除员工（标记为禁用而非真正删除）
     */
    public function delete(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (empty($data['id'])) {
            throw new Exception("缺少员工ID", 400);
        }

        // 执行更新（标记为禁用）
        $stmt = $this->conn->prepare("
            UPDATE users 
            SET status = 0
            WHERE id = :id
        ");
        if (!$stmt->execute([':id' => $data['id']])) {
            throw new Exception("禁用员工失败", 500);
        }

        echo json_encode([
            'code' => 200,
            'msg' => '禁用成功'
        ]);
    }

    /**
     * 获取员工列表
     */
    public function list(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(100, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = ["status = 1"]; // 只查询启用的员工
        $params = [];

        // 关键字搜索
        if (!empty($_GET['keyword'])) {
            $where[] = "(username LIKE :keyword OR real_name LIKE :keyword OR mobile LIKE :keyword)";
            $params[':keyword'] = '%' . $_GET['keyword'] . '%';
        }

        // 状态筛选
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "status = :status";
            $params[':status'] = intval($_GET['status']);
        }

        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        // 查询总数
        $countStmt = $this->conn->prepare("SELECT COUNT(*) FROM users {$whereClause}");
        $countStmt->execute($params);
        $total = (int)$countStmt->fetchColumn();

        // 查询数据
        $query = "
            SELECT 
                id, username, real_name, position,
                mobile,  status,
                create_time
            FROM users
            {$whereClause}
            ORDER BY create_time DESC
            LIMIT :offset, :limit
        ";
        
        $stmt = $this->conn->prepare($query);
        
        // 绑定分页参数
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        
        // 绑定其他参数
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        
        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }

    /**
     * 获取员工详情
     */
    public function detail(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        if (empty($_GET['id'])) {
            throw new Exception("缺少员工ID", 400);
        }

        $stmt = $this->conn->prepare("
            SELECT 
                id, username, real_name, position,
                mobile,  status,
                create_time
            FROM users
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $_GET['id']]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$member) {
            throw new Exception("员工不存在", 404);
        }

        echo json_encode([
            'code' => 200,
            'data' => $member
        ]);
    }
}